package com.ruoyi.tb.lmt.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.GuidUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.tb.lmt.domain.TbFdx;
import com.ruoyi.tb.lmt.domain.bo.TbFdxBo;
import com.ruoyi.tb.lmt.domain.vo.TbLmtrepairWorkdetailVo;
import com.ruoyi.tb.lmt.service.ITbFdxService;
import lombok.RequiredArgsConstructor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;

import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.tb.lmt.domain.vo.TbFdxdetailVo;
import com.ruoyi.tb.lmt.domain.bo.TbFdxdetailBo;
import com.ruoyi.tb.lmt.service.ITbFdxdetailService;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 预检详情
 *
 * @author ruoyi
 * @date 2024-01-03
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/xha-lmt/fdxdetail")
public class TbFdxdetailController extends BaseController {

    private final ITbFdxdetailService iTbFdxdetailService;

    private final ITbFdxService iTbFdxService;

    /**
     * 查询预检详情列表
     */

    @GetMapping("/list")
    public TableDataInfo<TbFdxdetailVo> list(TbFdxdetailBo bo, PageQuery pageQuery) {
        return iTbFdxdetailService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出预检详情列表
     */

    @Log(title = "临修详情", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TbFdxdetailBo bo, HttpServletResponse response) {
        List<TbFdxdetailVo> list = iTbFdxdetailService.queryList(bo);
        ExcelUtil.exportExcel(list, "临修详情", TbFdxdetailVo.class, response);
    }

    /**
     * 获取预检详情详细信息
     *
     * @param ID 主键
     */
    @SaCheckPermission("xha-lmt:fdxdetail:query")
    @GetMapping("/{ID}")
    public R<TbFdxdetailVo> getInfo(@NotNull(message = "主键不能为空")
                                    @PathVariable Long ID) {
        return R.ok(iTbFdxdetailService.queryById(ID));
    }

    /**
     * 新增预检详情
     */
    @SaCheckPermission("xha-lmt:fdxdetail:add")
    @Log(title = "预检详情", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody TbFdxdetailBo bo) {
        return toAjax(iTbFdxdetailService.insertByBo(bo));
    }

    /**
     * 修改预检详情
     */
    @SaCheckPermission("xha-lmt:fdxdetail:edit")
    @Log(title = "预检详情", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody TbFdxdetailBo bo) {
        return toAjax(iTbFdxdetailService.updateByBo(bo));
    }

    /**
     * 删除预检详情
     *
     * @param IDs 主键串
     */
    @SaCheckPermission("xha-lmt:fdxdetail:remove")
    @Log(title = "预检详情", businessType = BusinessType.DELETE)
    @DeleteMapping("/{IDs}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] IDs) {
        return toAjax(iTbFdxdetailService.deleteWithValidByIds(Arrays.asList(IDs), true));
    }

    @SaCheckPermission("xha-lmt:fdxdetail:addFdxdetail")
    @Log(title = "新增预检任务", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/fdxdetail")
    public R<Void> addFdxdetail(@Validated(AddGroup.class) @RequestBody Map map) {
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            TbFdxBo tbFdx = new TbFdxBo();
            Long Id = GuidUtil.getZcbhid();
            tbFdx.setID(Id);
            tbFdx.setLmtNumber((String) map.get("lmtNumber"));
            tbFdx.setLmtType((String) map.get("lmtType"));
            String requireStartTime = (String) map.get("requireStartTime");
            if (requireStartTime != null && !requireStartTime.isEmpty()) {
                tbFdx.setRequireStartTime(formatter.parse(requireStartTime));
            }
            tbFdx.setWorkType("预检");
            tbFdx.setStatus("新提报");
            LoginUser currentUser = LoginHelper.getLoginUser();
            tbFdx.setCreateTime(new Date());
            tbFdx.setCreateBy(currentUser.getUsername());
            iTbFdxService.insertByBo(tbFdx);

            //新增详情表
            TbFdxdetailBo tbFdxdetailBo = new TbFdxdetailBo();
            tbFdxdetailBo.setFdxId(Id);
            tbFdxdetailBo.setWorkName((String) map.get("workName"));
            tbFdxdetailBo.setWorkKind((String) map.get("workKind"));
            String workGroupIdString = (String) map.get("workCategoryId");
            if (workGroupIdString != null && !workGroupIdString.isEmpty()) {
                try {
                    Long workGroupId = Long.parseLong(workGroupIdString);
                    tbFdxdetailBo.setWorkCategoryId(workGroupId);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
            tbFdxdetailBo.setWorkCategory((String) map.get("workCategory"));
            tbFdxdetailBo.setWorkGroup((String) map.get("workGroup"));
            tbFdxdetailBo.setWorkGroup2((String) map.get("workGroup2"));
            tbFdxdetailBo.setWorkCategoryRemark((String) map.get("workCategoryRemark"));
            tbFdxdetailBo.setStatus("未提报");
            tbFdxdetailBo.setCheckReapirReqire((String) map.get("checkReapirReqire"));
            tbFdxdetailBo.setTaskUrl((String) map.get("taskUrl"));
            tbFdxdetailBo.setCreateTime(new Date());
            tbFdxdetailBo.setCreateBy(currentUser.getUsername());

            iTbFdxdetailService.insertByBo(tbFdxdetailBo);
            return R.ok();
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    @SaCheckPermission("xha-lmt:fdxdetail:updateFdxdetail")
    @Log(title = "修改预检任务", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/updateFdxdetail")
    public R<Void> updateFdxdetail(@Validated(AddGroup.class) @RequestBody Map map) {
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            TbFdxBo tbFdx = new TbFdxBo();
            Number fdxIdNumber = (Number) map.get("fdxId");
            tbFdx.setID(fdxIdNumber.longValue());
            //tbFdx.setID((Long) map.get("fdxId"));
            tbFdx.setLmtNumber((String) map.get("lmtNumber"));
            tbFdx.setLmtType((String) map.get("lmtType"));
            tbFdx.setRequireStartTime(map.get("requireStartTime") == null ? null : formatter.parse((String) map.get("requireStartTime")));
            LoginUser currentUser = LoginHelper.getLoginUser();
            tbFdx.setUpdateTime(new Date());
            tbFdx.setUpdateBy(currentUser.getUsername());
            iTbFdxService.updateByBo(tbFdx);

            //新增详情表
            TbFdxdetailBo tbFdxdetailBo = new TbFdxdetailBo();
            //Number id = (Number) map.get("id");
            //tbFdxdetailBo.setID(id.longValue());
            //tbFdxdetailBo.setID(Long.parseLong((String)  map.get("id")));
            Object idObj = map.get("id");

            // 检查idObj是否为Number类型
            if (idObj instanceof Number) {
                Number idNumber = (Number) idObj;
                tbFdxdetailBo.setID(idNumber.longValue());
            } else if (idObj instanceof String) { // 检查idObj是否为String类型
                tbFdxdetailBo.setID(Long.parseLong((String) idObj));
            } else {
                // 抛出异常或者处理其他类型的情况
                throw new IllegalArgumentException("The type of 'id' is neither Number nor String.");
            }
            tbFdxdetailBo.setFdxId(fdxIdNumber.longValue());
            tbFdxdetailBo.setWorkName((String) map.get("workName"));
            tbFdxdetailBo.setWorkKind((String) map.get("workKind"));
            tbFdxdetailBo.setWorkCategoryId(map.get("workCategoryId") == null ? null : Long.parseLong((String) map.get("workCategoryId")));
            tbFdxdetailBo.setWorkCategory((String) map.get("workCategory"));
            tbFdxdetailBo.setWorkCategoryRemark((String) map.get("workCategoryRemark"));
            tbFdxdetailBo.setCheckReapirReqire((String) map.get("checkReapirReqire"));
            tbFdxdetailBo.setRemark((String) map.get("remark"));
            tbFdxdetailBo.setWorkGroup((String) map.get("workGroup"));
            tbFdxdetailBo.setWorkGroup2((String) map.get("workGroup2"));
            tbFdxdetailBo.setWorkUser((String) map.get("workUser"));
            tbFdxdetailBo.setWorkUser2((String) map.get("workUser2"));
            tbFdxdetailBo.setTaskUrl((String) map.get("taskUrl"));
            tbFdxdetailBo.setUpdateTime(new Date());
            tbFdxdetailBo.setUpdateBy(currentUser.getUsername());

            iTbFdxdetailService.updateByBo(tbFdxdetailBo);
            return R.ok();
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    @SaCheckPermission("xha-lmt:fdxdetail:excelUpdate")
    @Log(title = "批量导入预检任务", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/update/excel")
    public R<Void> updateExcel(@RequestPart("file") MultipartFile file) {
        String s = iTbFdxService.updateExcel(file);
        if (StringUtils.isBlank(s)) {
            return R.ok();
        }
        return R.fail(s);
    }

    //导入模板
    //@SaCheckPermission("xha-lmt:fdxdetail:excelUpdate")
    @RequestMapping(value = "/excel/export")
    public void export(HttpServletRequest request, HttpServletResponse response) {
        iTbFdxService.export(request, response);
    }    //查询预检任务

    @GetMapping("/list/unreported")
    public TableDataInfo<TbFdxdetailVo> selectUnreported(String id, String lmtType, String lmtNumber, String status, PageQuery pageQuery) {
        return iTbFdxdetailService.selectUnreported(id, lmtType, lmtNumber, status, pageQuery);
    }
}
